﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
using ToolBoxPro;
using System.Globalization;
using System.Data.Common;
using LinqObj;
using System.Linq;
using System.IO;
using System.Security.AccessControl;

public partial class property : RedirectPage
{
    private int propertyID;
    private Property _property;
    ToolboxDataContext tdc = new ToolboxDataContext();
    private Agent_Group group;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ((Label)Master.FindControl("lblTitle")).Text = "Add a Property";
            ((System.Web.UI.HtmlControls.HtmlImage)Master.FindControl("imgHeading")).Src = "images/icon_house.gif";
            
        }
        
        int Int32Val = 0;
        string t = null;
        
        if (Request.Form["task_num"] != null)
            t = Request.Form["task_num"].ToString();
        else if (this.hd_PropertyID.Value.Trim() != "")
            t = this.hd_PropertyID.Value;

        if (t != null && t != "")
        {
            this.propertyID = Int32.Parse(t);
            this._property = Property.GetProperty(this.propertyID);
        }
        
        if (!IsPostBack)
        {
            bindAgentRoles();
            bindSaleMethod();

            if (t != null && t != "")
            {
                bindCampaignStatus();
                populatePropertyData(propertyID);
                populateVendorData(propertyID);
                disableAllInputBox();
                propertydiv.Visible = true;
                this.dl_campaignStatus.Visible = true;

                /* COMMENTED BY KAUSHAL GAJJAR */
                //this.h4_title.InnerText = "Submit a Change to the Property";
                //this.p_hint.InnerText = "Please modify the information and click submit to make the change";
                
                
                this.switchButton.Visible = true;
                this.hd_PropertyID.Value = this.propertyID.ToString();
                this.addProperty.Visible = false;
                this.dl_campaignStatus.Visible = true;

                campaignslist.Visible = true;
            }
            else if (t == null)
            {
                campaignslist.Visible = false;
                propertydiv.Visible = false;
                enableAllInputBox();
                
                //bindAgentRoles();
                //bindSaleMethod();
                //bindCampaignStatus();

                this.dl_campaignStatus.Visible = false;
                this.switchButton.Visible = false;

                /* COMMENTED BY KAUSHAL GAJJAR */
                //this.h4_title.InnerText = "Creat a Property";
                //this.p_hint.InnerText = "Please Enter the property information and agent information and press Submit to create a Property.";
            }
        }

        displayCampaignHistory(propertyID);
    }

    public void bindAgentRoles()
    {
        List<Agent> agentList = (List<Agent>)Agent.GetAgentListByAgentGroupID(Session[FormContract.AGENT_GROUP_ID].ToString());
        agentList.Insert(0, new Agent(0, ""));

        this.dl_advertisingAgent.DataSource = agentList;
        this.dl_advertisingAgent.DataTextField = "agent_name";
        this.dl_advertisingAgent.DataValueField = "agent_id";
        //this.dl_advertisingAgent.Items.Add(new ListItem("0", "Please Select"));
        this.dl_advertisingAgent.DataBind();

        this.dl_listingAgent.DataSource = agentList;
        this.dl_listingAgent.DataTextField = "agent_name";
        this.dl_listingAgent.DataValueField = "agent_id";
        //this.dl_listingAgent.Items.Add(new ListItem("0", "Please Select"));
        this.dl_listingAgent.DataBind();

        this.dl_managingAgent.DataSource = agentList;
        this.dl_managingAgent.DataTextField = "agent_name";
        this.dl_managingAgent.DataValueField = "agent_id";
        //this.dl_managingAgent.Items.Add(new ListItem("0", "Please Select"));
        this.dl_managingAgent.DataBind();

    }

    private void bindSaleMethod()
    {
        List<Vendor_Status> list = (List<Vendor_Status>)(Vendor_Status.GetStatusList());
        list.Insert(0, new Vendor_Status());
        this.dl_sale_method.DataSource = list;
        this.dl_sale_method.DataValueField = "vendor_status_id";
        this.dl_sale_method.DataTextField = "vendor_status1";
        this.dl_sale_method.DataBind();
    }

    private void bindCampaignStatus()
    {
        List<Campaign_Status> a;

        if (this._property._CampaignStatus.Equals(Campaign.STATUS_INACTIVE, StringComparison.CurrentCultureIgnoreCase))
            a = Campaign.LoadCampaignStatusList(Campaign.STATUS_ARCHIVED);
        else
            a = Campaign.LoadCampaignStatusList(Campaign.STATUS_ARCHIVED);

        this.dl_campaignStatus.DataSource = a;
        this.dl_campaignStatus.DataValueField = "status_id";
        this.dl_campaignStatus.DataTextField = "status";
        this.dl_campaignStatus.DataBind();

        for (int index = 0; index < a.Count; index++)
        {
            if (a[index].status_id == this._property.campaign_status)
            {
                this.dl_campaignStatus.SelectedIndex = index;
                break;
            }
        }
    }

    private void populatePropertyData(int propertyID)
    {
        Property currentProperty = Property.GetProperty(propertyID);
        this.txt_address1.Text = currentProperty.address1;
        this.txt_address2.Text = currentProperty.address2;
        this.txt_state.Text = currentProperty.state;
        this.txt_suburb.Text = currentProperty.suburb;
        this.txt_postcode.Text = currentProperty.postcode;

        if(currentProperty.schedule_date != null)
            txt_ScheduleDate.Text = String.Format("{0:dd/MM/yyyy}", currentProperty.schedule_date);
        

        /*  CHANGED BY KAUSHAL */
        if (currentProperty.advertising_agent.HasValue)
            dl_advertisingAgent.Items.FindByValue(currentProperty.advertising_agent.Value.ToString()).Selected = true;

        if (currentProperty.listing_agent.HasValue)
            dl_listingAgent.Items.FindByValue(currentProperty.listing_agent.Value.ToString()).Selected = true;

        if (currentProperty.managing_agent.HasValue)
            dl_managingAgent.Items.FindByValue(currentProperty.managing_agent.Value.ToString()).Selected = true;

        if (currentProperty.vendor_status.HasValue)
            dl_sale_method.Items.FindByValue(currentProperty.vendor_status.Value.ToString()).Selected = true;



        //this.dl_advertisingAgent.SelectedIndex = currentProperty.advertising_agent == null ? 0 : currentProperty.advertising_agent.Value;
        //this.dl_listingAgent.SelectedIndex = currentProperty.listing_agent == null ? 0 : currentProperty.listing_agent.Value;
        //this.dl_managingAgent.SelectedIndex = currentProperty.managing_agent == null ? 0 : currentProperty.managing_agent.Value;
        //this.dl_sale_method.SelectedIndex = currentProperty.vendor_status == null ? 0 : currentProperty.vendor_status.Value;

        txtHeading.Text = currentProperty.PropertyHeading;
        txtareadDesc.InnerText = currentProperty.Description;
    }

    private void populateVendorData(int _propertyID)
    {
        Vendor_Detail vendor = Property.GetProperty(_propertyID).Vendor_Detail;

        if (vendor != null)
        {
            this.txt_VendorAddress1.Text = vendor.post_address1;
            this.txt_VendorAddress2.Text = vendor.post_address2;
            this.txt_VendorPostcode.Text = vendor.post_code;
            this.txt_VendorState.Text = vendor.post_state;
            this.txt_VendorSuburb.Text = vendor.post_suburb; ;
            this.txt_ContactNumber.Text = vendor.contact_number;
            this.txt_FamilyName.Text = vendor.family_name;
            this.txt_GivenName.Text = vendor.given_name;
            txt_Email.Text = vendor.email;
            txt_Mobile.Text = vendor.mobile_number;
        }
    }

    private void disableAllInputBox()
    {
        this.txt_address1.ReadOnly = true;
        this.txt_address2.ReadOnly = true;
        this.txt_postcode.ReadOnly = true;
        this.txt_state.ReadOnly = true;
        this.txt_suburb.ReadOnly = true;
        this.dl_advertisingAgent.Enabled = false;
        this.dl_listingAgent.Enabled = false;
        this.dl_sale_method.Enabled = false;
        this.dl_managingAgent.Enabled = false;
        this.txt_Email.ReadOnly = true;
        this.txt_FamilyName.ReadOnly = true;
        this.txt_VendorPostcode.ReadOnly = true;
        txt_ScheduleDate.Enabled = false;
        this.txt_VendorAddress2.ReadOnly = true;
        this.txt_VendorAddress1.ReadOnly = true;
        this.txt_VendorSuburb.ReadOnly = true;
        this.txt_VendorState.ReadOnly = true;
        txt_GivenName.ReadOnly = true;
        this.txt_Email.ReadOnly = true;
        this.txt_ContactNumber.ReadOnly = true;
        this.txt_Mobile.ReadOnly = true;
        this.check_IsPostAddress.Enabled = false;
        this.dl_campaignStatus.Enabled = false;

        txtHeading.ReadOnly = true;
        txtareadDesc.Disabled = true;
    }

    private void enableAllInputBox()
    {
        this.txt_address1.ReadOnly = false;
        this.txt_address2.ReadOnly = false;
        this.txt_postcode.ReadOnly = false;
        this.txt_state.ReadOnly = false;
        this.txt_suburb.ReadOnly = false;
        this.dl_advertisingAgent.Enabled = true;
        this.dl_listingAgent.Enabled = true;
        this.dl_sale_method.Enabled = true;
        this.dl_managingAgent.Enabled = true;
        this.txt_Email.ReadOnly = false;
        this.txt_FamilyName.ReadOnly = false;
        this.txt_VendorPostcode.ReadOnly = false;
        this.txt_VendorAddress2.ReadOnly = false;
        this.txt_VendorAddress1.ReadOnly = false;
        this.txt_VendorSuburb.ReadOnly = false;
        this.txt_VendorState.ReadOnly = false;
        this.txt_Email.ReadOnly = false;
        this.txt_ContactNumber.ReadOnly = false;
        this.txt_Mobile.ReadOnly = false;
        this.check_IsPostAddress.Enabled = true;
        this.dl_campaignStatus.Enabled = true;
        this.check_IsPostAddress.Enabled = true;
        txt_GivenName.ReadOnly = false;
        txtHeading.ReadOnly = false;
        txtareadDesc.Disabled = false;
        txt_ScheduleDate.Enabled = true;
    }

    private void displayCampaignHistory(int propertyID)
    {
        if (propertyID <= 0)
            return;

        List<Campaign> campaigns = Campaign.GetAllCampaigns(propertyID);
        CampaignListBuilder builder = new CampaignListBuilder(campaigns);
        this.ph_Campaigns.Controls.Add(builder.BuildCampaignList());

        //for (int i = 0; i < builder.buttons.Count; i++)
        //{
        //    builder.link[i].Click += Campaign_Click;
        //}
    }     

    //private void BindAgentData(String strPropertyID)
    //{

    //    int propertyID = Convert.ToInt32(strPropertyID);
    //    Property property = Property.GetProperty(propertyID);
    //    this.txt_address1.Text = property.address1;
    //    this.txt_address2.Text = property.address2;
    //    this.txt_postcode.Text = property.postcode;
    //    this.txt_state.Text = property.state;
    //    this.txt_suburb.Text = property.suburb;
    //}

    ////protected void Campaign_Click(object sender, EventArgs e)
    ////{
    ////    Response.Redirect("~/artwork.aspx?campaign_id=", false);
    ////}

    protected void addProperty_Click(object sender, ImageClickEventArgs e)
    {
        string msg="";
        string addr1 = "", addr2 = "", suburb = "";

        Int32 val;
        
        if (Int32.TryParse(this.hd_PropertyID.Value, out val))
            this.propertyID = Int32.Parse(this.hd_PropertyID.Value);
        
        Vendor_Detail vendor;
        Property property;


        if (propertyID > 0)
        {
            msg = "edit";
            property = Property.GetProperty(this.propertyID);
            
            addr1 = property.address1;
            addr2 = property.address2;
            suburb = property.suburb;

            vendor = property.Vendor_Detail;            
        }
        else
        {
            msg = "add";
            property = new Property();
            vendor = new Vendor_Detail();            
        }

        vendor.mobile_number = this.txt_Mobile.Text.Trim();
        vendor.contact_number = this.txt_ContactNumber.Text.Trim();
        vendor.email = this.txt_Email.Text.Trim();
        vendor.post_address1 = this.txt_VendorAddress1.Text.Trim();
        vendor.post_address2 = this.txt_VendorAddress2.Text.Trim();
        vendor.post_state = this.txt_VendorState.Text.Trim();
        vendor.post_suburb = this.txt_VendorSuburb.Text.Trim();
        vendor.post_code = this.txt_VendorPostcode.Text.Trim();
        vendor.given_name = this.txt_GivenName.Text.Trim();
        vendor.family_name = this.txt_FamilyName.Text.Trim();

        property.address1 = this.txt_address1.Text.ToString().Trim();
        property.address2 = this.txt_address2.Text.ToString().Trim();
        property.state = this.txt_state.Text.ToString().Trim();
        property.suburb = this.txt_suburb.Text.ToString().Trim();        

        property.postcode = this.txt_postcode.Text.ToString().Trim();
        property.last_modified_date = DateTime.Now;
        if (this.txt_ScheduleDate.Text.Trim() != "")
            property.schedule_date = DateTime.Parse(this.txt_ScheduleDate.Text.Trim(), CultureInfo.CurrentCulture);

        property.setMangingAgent(this.dl_managingAgent.SelectedValue);
        property.setAdvAgent(this.dl_advertisingAgent.SelectedValue);
        property.setAgent(((Agent)Session[FormContract.AGENT]).agent_id.ToString());
        property.setListingAgent(this.dl_listingAgent.SelectedValue);
        property.setVendorStatus(this.dl_sale_method.SelectedValue);
        property.setAgentGroup((int)Session[FormContract.AGENT_GROUP_ID]);

        property.PropertyHeading = txtHeading.Text;
        property.Description = txtareadDesc.InnerText;

        if (property.Vendor_Detail == null)
            property.Vendor_Detail = vendor;

        property.user_id = ((Toolbox_User)Session[FormContract.USER]).user_id;
        if (this.dl_campaignStatus.Visible)
            property.SetCampaignStatus(Convert.ToInt32(this.dl_campaignStatus.SelectedValue));
        else
            property.SetCampaignStatus(Campaign.STATUS_INACTIVE);
        this.hd_PropertyID.Value = property.property_id.ToString();
        Property.Insert_Update(property);        

        Campaign campaign = Campaign.GetCurrentCampaignByProperty(property.property_id);

        if (campaign == null)
        {
            campaign = new Campaign();
            campaign.agent_id = Convert.ToInt32(((Agent)Session[FormContract.AGENT]).agent_id.ToString());
            campaign.property_id = property.property_id;
            campaign.user_id = ((Toolbox_User)Session[FormContract.USER]).user_id;
            Campaign.AddCampaign(campaign);
        }

        campaign.SetCampaignStatus(property.campaign_status);
        Campaign.SubmitChanges();


        int agentGroupID = Convert.ToInt32(Session[FormContract.AGENT_GROUP_ID]);
        this.group = Agent_Group.GetAgentGroup(agentGroupID);

        if (propertyID > 0)
        {
            if ((!addr1.Equals(txt_address1.Text.Trim())) || (!addr2.Equals(txt_address2.Text.Trim())) || (!suburb.Equals(txt_suburb.Text.Trim())))
            {
                string fromfilename = Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + property.property_id + " " + addr1 + " " + addr2 + " " + suburb);
                string tofilename = Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + property.property_id + " " + txt_address1.Text.Trim() + " " + txt_address2.Text.Trim() + " " + txt_suburb.Text.Trim());
                if (Directory.Exists(fromfilename))
                {                                     
                    Directory.Move(fromfilename, tofilename);
                }
                else
                    property.CreateDir(tofilename);
            }
        }
        else
        {
            property.CreateDir();
        }


        this.hd_PropertyID.Value = property.property_id.ToString();
        
        //if (msg == "edit")
        //    Response.Redirect("login.aspx");

        Response.Redirect("propertylist.aspx?msg=" + msg, false);
    }

    protected void switchButton_Click(object sender, ImageClickEventArgs e)
    {
        enableAllInputBox();
        //if (this.addProperty.Visible == true)
        //   this.addProperty.Visible = false;
        //else
        switchButton.Visible = false;
        this.addProperty.Visible = true;
    }
    
    protected void bt_ShoppingCart_Click(object sender, ImageClickEventArgs e)
    {
        string _propertyID = this.hd_PropertyID.Value;
        if (_propertyID != null && _propertyID != "")
            Server.Transfer("~/shoppingcart.aspx");
    }
    protected void dl_campaignStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        string t = null;

        if (Request.Form["task_num"] != null)
            t = Request.Form["task_num"].ToString();
        else if (this.hd_PropertyID.Value.Trim() != "")
            t = this.hd_PropertyID.Value;

        if (t != null && t != "")
        {
            this.propertyID = Int32.Parse(t);
            //this._property = Property.GetProperty(this.propertyID);
        }

        var Campaign = (from c in tdc.Campaigns
                        where c.property_id == propertyID
                        select c).Single();

        var orders = (from o in tdc.Orders
                      where o.campaign_id == Campaign.campaign_id
                      select o);
        if (orders.Count() > 0)
        {
            if (dl_campaignStatus.SelectedItem.Text.ToLower().Equals("inactive"))
            {
                string script = "";
                script += "<script>";
                script += "alert('This property has order(s).')";
                script += "</script>";
                ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", script,false);
            }
        }
    }
}
